from libs.base.model import BaseModel
from libs.tools.jwt_helper import JwtHelper


class LoginModel(BaseModel):

    def __init__(self, handler):
        super(LoginModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def start(self, opts):
        """
        登录
        """
        selects = ["user_id", "password"]
        wheres = {"account": opts["account"], "data_status": 1}
        await self.db.select("auth_user", selects, wheres)
        data = self.db.fetchone()
        if data and data["password"] == opts["password"]:
            token = JwtHelper().make_web_token(data["user_id"])
            return self.set_res_info(0, data={"auth_token": token})
        return self.set_res_info(4007)


class UserModel(BaseModel):

    def __init__(self, handler):
        super(UserModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def get_user_info(self):
        """
        获取用户基本信息和权限
        """
        data = {
            "user_id": self.user["user_id"],
            "account": self.user["account"],
            "name": self.user["name"],
            "email": self.user["email"],
            "phone_number": self.user["phone_number"],
            "create_time": self.user["create_time"],
            "permissions": self.user["permissions"]
        }
        return self.set_res_info(0, data=data)
